/**
 * 
 */
package io.dora.remoting;


import io.dora.rpc.RpcFutureResult;
import io.dora.rpc.RpcResponse;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 服务调用方响应处理器
 * 
 * @author zhaohongbo
 * 
 */
public class ConsumerHandler extends ChannelHandlerAdapter {
	
	private Logger logger = LoggerFactory.getLogger(ConsumerHandler.class);

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		logger.error("Unexpected exception from downstream:"+ cause.getMessage());
		ctx.close();
		logger.error("Client exited on exception");
		super.exceptionCaught(ctx, cause);
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		super.channelActive(ctx);
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		RpcResponse response = (RpcResponse) msg;
		Object responseData = response.getData();
		if (responseData == null) { 
			responseData = new Object();
		}
        RpcFutureResult.FUTURE_RESULT.put(response.getId(), responseData);
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();
		super.channelReadComplete(ctx);
	}
}
